﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;

namespace Sparrow.VisualStudio.Debugger.RouteVisualizer
{
    public class Serializer : Microsoft.VisualStudio.DebuggerVisualizers.VisualizerObjectSource
    {
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            RouteCollection routes = RouteTable.Routes;

            if (target != null && target is RouteCollection)
            {
                routes = target as RouteCollection;
            }


            var data = new RouteTransporterCollection();

            
            foreach (var route in routes)
            {
                if (route is Route)
                {
                    data.Transporters.Add(new MvcRouteTransporter(route as Route));
                }
                else if (route.GetType().IsSerializable)
                {
                    data.Transporters.Add(new BinaryRouteTransporter(route));
                }
                else
                {
                    data.Transporters.Add(new JsonRouteTransporter(route));
                }
            }



            if (HttpContext.Current != null)
            {
                var request = HttpContext.Current.Request;
                data.AppRelativeCurrentExecutionFilePath = request.AppRelativeCurrentExecutionFilePath;
                data.PathInfo = request.PathInfo;
            }
            else
            {
                data.AppRelativeCurrentExecutionFilePath = "~/";
                data.PathInfo = "";
            }

            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(outgoingData, data);

        }
    }
}
